package com.znsd.exam.controllor;

import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.znsd.entitys.ClassInfo;
import com.znsd.entitys.CourseInfo;
import com.znsd.entitys.ExamPaperInfo;
import com.znsd.entitys.ExamPlan;
import com.znsd.entitys.SpecialtyInfo;
import com.znsd.entitys.Users;
import com.znsd.exam.service.ExamHistoryPaperService;
import com.znsd.exam.service.ExamPaperService;
import com.znsd.exam.service.ExamPlanService;
import com.znsd.exam.service.SpecialtyService;
import com.znsd.exam.service.UserServicePan;

/**
  *
  * <p>Title: ExamPlanInfoHandler</p>
  * <p>Description: 考试安排</p>
  * @author: taohan
  * @date: 2018-8-22
  * @time: 下午4:06:51
  * @version: 1.0
  */

@Controller
@SuppressWarnings("all")
public class ExamPlanControllor {

	private ExamPaperInfo examPaper= new ExamPaperInfo();
	@Autowired
	private ExamPlanService examPlanInfoService;
	@Autowired
	private SpecialtyService courseInfoService;
	@Autowired
	private ExamPaperService examPaperInfoService;
	@Autowired
	private ExamHistoryPaperService examHistoryService;
	@Autowired
	private UserServicePan userService;
	
	private Logger logger = Logger.getLogger(ExamPlanControllor.class);
	
	
	/**
	 * 获取所有待考记录
	 * @return
	 */
	@RequestMapping("/examPlans")
	public ModelAndView getExamPlans() {
		ModelAndView model = new ModelAndView();
		model.setViewName("admin/examPlans");
		logger.info("获取待考考试信息");
		
		List<ExamPlan> examPlans = examPlanInfoService.getExamPlans(null);
		List<ExamPlan> plansTwo = examPlanInfoService.getExamPlansTwo();
		if(examPlans.size()<plansTwo.size()) {
			for (int i = 0; i < examPlans.size(); i++) {
				plansTwo.get(i).setClazz(examPlans.get(i).getClazz());
			}
			model.addObject("examPlans", plansTwo);
		}else {
			model.addObject("examPlans", examPlans);
		}
		
		return model;
	}
	
	
	/**
	 * 预添加
	 * @return
	 */
	@RequestMapping("/preAddep")
	public ModelAndView preAddep() {
		ModelAndView model = new ModelAndView();
		model.setViewName("admin/examPlanedit");
		
		//获取所有班级信息
		List<ClassInfo> classes = examPlanInfoService.getClasses(null);
		model.addObject("classes", classes);
		//获取所有科目信息
		List<SpecialtyInfo> courses = courseInfoService.getCourseList();
		model.addObject("courses", courses);
		//获取所有的试卷信息 -- 纯净的
		List<ExamPaperInfo> examPapers = examPaperInfoService.getExamPapersClear();
		model.addObject("examPapers", examPapers);
		
		return model;
	}

	/**
	 * 添加待考信息
	 * @param examPlan 考试安排记录信息
	 * @return
	 */
	@RequestMapping(value="examPlan", method=RequestMethod.POST)
	public String isAddExamPlan(ExamPlan examPlan) {
		logger.info("添加待考记录："+examPlan);
		examPlanInfoService.addExamPlan(examPlan);
		
		return "redirect:examPlans";
	}
	
	
	/**
	 * 预修改
	 * @param examPlanId 考试安排(待考)编号
	 * @return
	 */
	@RequestMapping(value="/preUpdateep/{examPlanId}", method=RequestMethod.GET)
	public ModelAndView preUpdateep(@PathVariable("examPlanId") Integer examPlanId) {
		ModelAndView model = new ModelAndView();
		model.setViewName("/admin/examPlanedit");
		
		//获取所有班级信息
		List<ClassInfo> classes = examPlanInfoService.getClasses(null);
		model.addObject("classes", classes);
		//获取所有科目信息
		List<SpecialtyInfo> courses = courseInfoService.getCourseList();
		model.addObject("courses", courses);
		//获取所有的试卷信息 -- 纯净的(简单的)
		List<ExamPaperInfo> examPapers = examPaperInfoService.getExamPapersClear();
		model.addObject("examPapers", examPapers);
		//获取当前修改对象
		ExamPlan examPlanWithUpdate = examPlanInfoService.getExamPlanById(examPlanId);
		logger.info("获取要修改的待考记录："+examPlanWithUpdate);
		List<ExamPlan> list = examPlanInfoService.getExamPlansTwo();
		for (int i = 0; i < list.size(); i++) {
			if(list.get(i).getExamPlanId()==examPlanId) {
				if(examPlanWithUpdate.getClazz()==null) {
					ExamPlan examPlanByIdTwo = examPlanInfoService.getExamPlanByIdTwo(examPlanId);
					model.addObject("examPlan", examPlanByIdTwo);
				}else {
					model.addObject("examPlan", examPlanWithUpdate);
				}
			}
		}
		return model;
	}
	
	
	/**
	 * 修改待考信息
	 * @param examPlan 待考记录
	 * @return
	 */
	@RequestMapping(value="preUpdateep/examPlan", method=RequestMethod.PUT)
	public String isUpdateExamPlan(ExamPlan examPlan) {
		logger.info("修改待考记录："+examPlan);
		examPlanInfoService.updateExamPlan(examPlan);
		
		return "redirect:../examPlans";
	}
	
	
	/**
	 * 查询学生待考信息
	 * @param classId 学生所在班级编号
	 * @param gradeId 学生所在年级百年好
	 * @param studentId 学生编号
	 * @return
	 */
	@RequestMapping("/willexams")
	public ModelAndView getStudentWillExam(
			@RequestParam("clazz_id") Integer clazz_id,
			@RequestParam(value="user_id", required=false) Integer user_id) {
		logger.info("查询学生 "+user_id+"(NULL-未指定)待考信息 班级："+clazz_id);
		ModelAndView model = new ModelAndView();
		model.setViewName("/reception/examCenter");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("classId", clazz_id);
		
		List<ExamPlan> examPlans = examPlanInfoService.getStudentWillExam(map);
		model.addObject("examPlans", examPlans);
		
		return model;
	}
	
	
	
	/**
	 * 定时刷新考试安排记录，将过期考试移除
	 * 周一至周五 每隔15分钟刷新一次
	 */
	@Scheduled(cron="0 */15 * * * MON-FRI")
	public void refreshExamPlan() {
		List<ExamPlan> examPlans = examPlanInfoService.getExamPlans(null);
		logger.info("刷新待考记录, SIZE "+examPlans.size());
		if (examPlans.size() > 0) {
			for (ExamPlan examPlanInfo : examPlans) {
				String beginTime = examPlanInfo.getBeginTime().toString();
				int examPaperTime = examPlanInfo.getExamPaper().getExamPaperTime();
				/** 验证是否可移除 */
				if (validateExamPaerBeOverdue(beginTime, examPaperTime)) {
					logger.info("待考试卷 "+examPlanInfo.getExamPaper().getExamPaperId()+" 已经过期，即将移除");
					//移除过期考试安排
					int row = examPlanInfoService.removeExamPlan(examPlanInfo.getExamPlanId());
				} else {
					logger.info("待考试卷 "+examPlanInfo.getExamPaper().getExamPaperId()+" 暂未过期，无法移除");
					continue;
				}
			} 
		}
	}
	
	
	/**
	 * 验证试卷是否过期
	 * @param beginTime 考试开始时间
	 * @param examTime 考试时间
	 * @return
	 */
	private boolean validateExamPaerBeOverdue(String beginTime, int examTime) {
		boolean flag = false;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date beginTimeDate = sdf.parse(beginTime);
			Long beginTimeTime = beginTimeDate.getTime();
			
			/** 转换考试时间为毫秒单位 */
			int examTimeSecond = examTime * 60 * 1000;
			
			Date nowDate = new Date();
			Long nowDateTime = nowDate.getTime();
			
			/** 当前时间超过了 考试结束时间，即为过期记录 */
			if(nowDateTime > (beginTimeTime+examTimeSecond)) {
				flag = true;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return flag;
	}
	
	
	/**
	 * 教师移除考试安排记录
	 * @param examPlanId
	 * @return
	 */
	@RequestMapping(value="/del/{examPlanId}")
	public String isDelExamPlan(
			@PathVariable("examPlanId") Integer examPlanId) {
		logger.info("教师 移除考试安排 "+examPlanId);
		
		int row = examPlanInfoService.removeExamPlan(examPlanId);
		return "redirect:../examPlans";
	}
	@ResponseBody
	@RequestMapping(value="/student/getExams",method = RequestMethod.GET)
	public int getExams(String user_id) {
		Users user = userService.getStudentById(Integer.parseInt(user_id));
		Date date = Calendar.getInstance().getTime();
		int count=0;
		List<ExamPlan> plansTwo = examPlanInfoService.getExamPlansTwo();
		for (int i = 0; i < plansTwo.size(); i++) {
			Map<String,Object> map=new HashMap<>();
			map.put("user_name", user.getUser_name());
			map.put("classId", user.getClassId());
			map.put("date",date);
			Integer examPaperTime = plansTwo.get(i).getExamPaper().getExamPaperTime();
			int minutes = date.getMinutes();
			String beginTime = plansTwo.get(i).getBeginTime();
			SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Date date2=null;
			try {
				date2 = sim.parse(beginTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if(minutes+examPaperTime>=60) {
				minutes=minutes+examPaperTime;
				minutes-=60;
				int a=(minutes+examPaperTime)/60;
				date2.setHours(date2.getHours()+a);
				date2.setMinutes(minutes);
			}else {
				
			}
			map.put("endTime", date2);
			count+= examPlanInfoService.getExamCount(map);
		}
		return count;
	}
}
